<template>
  <div class="user-report">
    <!-- 页面标题 -->
    <div class="report-header">
      <h2 class="page-title">用户分析报表</h2>
      <div class="header-actions">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          @change="handleDateChange"
        />
        <el-button type="primary" icon="Refresh" @click="refreshData">
          刷新数据
        </el-button>
        <el-button type="success" icon="Download" @click="handleExport">
          导出报表
        </el-button>
      </div>
    </div>

    <!-- 统计概览 -->
    <el-row :gutter="20" class="overview-row">
      <el-col :span="6" :xs="12">
        <div class="overview-card">
          <div class="card-icon primary">
            <el-icon><User /></el-icon>
          </div>
          <div class="card-content">
            <div class="card-number">{{ overview.totalUsers || 0 }}</div>
            <div class="card-label">总用户数</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6" :xs="12">
        <div class="overview-card">
          <div class="card-icon success">
            <el-icon><UserFilled /></el-icon>
          </div>
          <div class="card-content">
            <div class="card-number">{{ overview.activeUsers || 0 }}</div>
            <div class="card-label">活跃用户</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6" :xs="12">
        <div class="overview-card">
          <div class="card-icon warning">
            <el-icon><Plus /></el-icon>
          </div>
          <div class="card-content">
            <div class="card-number">{{ overview.newUsers || 0 }}</div>
            <div class="card-label">新增用户</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6" :xs="12">
        <div class="overview-card">
          <div class="card-icon danger">
            <el-icon><CircleClose /></el-icon>
          </div>
          <div class="card-content">
            <div class="card-number">{{ overview.inactiveUsers || 0 }}</div>
            <div class="card-label">停用用户</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-row">
      <!-- 用户注册趋势 -->
      <el-col :span="12" :xs="24">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>用户注册趋势</span>
              <el-radio-group v-model="trendPeriod" size="small" @change="handleTrendPeriodChange">
                <el-radio-button label="7">近7天</el-radio-button>
                <el-radio-button label="30">近30天</el-radio-button>
                <el-radio-button label="90">近90天</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div ref="registerTrendChartRef" class="chart-container"></div>
        </el-card>
      </el-col>

      <!-- 用户状态分布 -->
      <el-col :span="12" :xs="24">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>用户状态分布</span>
            </div>
          </template>
          <div ref="userStatusChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 详细分析 -->
    <el-row :gutter="20" class="detail-row">
      <!-- 部门用户分布 -->
      <el-col :span="8" :xs="24">
        <el-card class="detail-card">
          <template #header>
            <div class="card-header">
              <span>部门用户分布</span>
            </div>
          </template>
          <div ref="deptDistributionChartRef" class="chart-container-small"></div>
        </el-card>
      </el-col>

      <!-- 角色分布 -->
      <el-col :span="8" :xs="24">
        <el-card class="detail-card">
          <template #header>
            <div class="card-header">
              <span>角色分布</span>
            </div>
          </template>
          <div ref="roleDistributionChartRef" class="chart-container-small"></div>
        </el-card>
      </el-col>

      <!-- 用户活跃度 -->
      <el-col :span="8" :xs="24">
        <el-card class="detail-card">
          <template #header>
            <div class="card-header">
              <span>用户活跃度</span>
            </div>
          </template>
          <div class="activity-list">
            <div v-for="(item, index) in activityData" :key="index" class="activity-item">
              <div class="activity-user">{{ item.userName }}</div>
              <div class="activity-score">
                <el-progress
                  :percentage="item.score"
                  :color="getActivityColor(item.score)"
                  :show-text="false"
                  :stroke-width="8"
                />
                <span class="score-text">{{ item.score }}%</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>用户详细数据</span>
          <div class="table-actions">
            <el-input
              v-model="searchText"
              placeholder="搜索用户"
              clearable
              style="width: 200px"
              @input="handleSearch"
            />
          </div>
        </div>
      </template>
      
      <el-table v-loading="tableLoading" :data="userData" stripe>
        <el-table-column prop="userName" label="用户名" width="120" />
        <el-table-column prop="nickName" label="昵称" width="120" />
        <el-table-column prop="deptName" label="部门" width="120" />
        <el-table-column prop="roleName" label="角色" width="120" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === '0' ? 'success' : 'danger'">
              {{ row.status === '0' ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column prop="lastLoginTime" label="最后登录" width="160" />
        <el-table-column prop="loginCount" label="登录次数" width="100" />
        <el-table-column prop="operCount" label="操作次数" width="100" />
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        v-model:page="queryForm.pageNum"
        v-model:limit="queryForm.pageSize"
        :total="total"
        @pagination="getUserData"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { getUserReport, exportUserReport } from '@/api/report/user'
import Pagination from '@/components/Pagination/index.vue'

// 响应式数据
const dateRange = ref<string[]>([])
const trendPeriod = ref('7')
const searchText = ref('')
const tableLoading = ref(false)
const total = ref(0)

// 概览数据
const overview = reactive({
  totalUsers: 0,
  activeUsers: 0,
  newUsers: 0,
  inactiveUsers: 0,
})

// 活跃度数据
const activityData = ref<any[]>([])

// 用户数据
const userData = ref<any[]>([])

// 查询参数
const queryForm = reactive({
  pageNum: 1,
  pageSize: 10,
  startDate: '',
  endDate: '',
  userName: '',
})

// 图表引用
const registerTrendChartRef = ref()
const userStatusChartRef = ref()
const deptDistributionChartRef = ref()
const roleDistributionChartRef = ref()

// 图表实例
let registerTrendChart: echarts.ECharts
let userStatusChart: echarts.ECharts
let deptDistributionChart: echarts.ECharts
let roleDistributionChart: echarts.ECharts

// 获取报表数据
const getReportData = async () => {
  try {
    const params = {
      startDate: dateRange.value?.[0] || '',
      endDate: dateRange.value?.[1] || '',
      period: trendPeriod.value,
    }
    
    const { data } = await getUserReport(params)
    
    // 更新概览数据
    Object.assign(overview, data.overview)
    
    // 更新活跃度数据
    activityData.value = data.activityData || []
    
    // 渲染图表
    nextTick(() => {
      renderRegisterTrendChart(data.registerTrend || [])
      renderUserStatusChart(data.statusDistribution || [])
      renderDeptDistributionChart(data.deptDistribution || [])
      renderRoleDistributionChart(data.roleDistribution || [])
    })
  } catch (error) {
    console.error('获取用户报表数据失败:', error)
    ElMessage.error('获取用户报表数据失败')
  }
}

// 获取用户数据表格
const getUserData = async () => {
  tableLoading.value = true
  try {
    const params = {
      ...queryForm,
      startDate: dateRange.value?.[0] || '',
      endDate: dateRange.value?.[1] || '',
    }
    
    // 这里应该调用实际的API，暂时使用模拟数据
    userData.value = generateMockUserData()
    total.value = 50
  } catch (error) {
    console.error('获取用户数据失败:', error)
  } finally {
    tableLoading.value = false
  }
}

// 渲染注册趋势图表
const renderRegisterTrendChart = (data: any[]) => {
  if (!registerTrendChartRef.value) return
  
  if (!registerTrendChart) {
    registerTrendChart = echarts.init(registerTrendChartRef.value)
  }
  
  const dates = data.map(item => item.date)
  const counts = data.map(item => item.count)
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: dates
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: counts,
        type: 'line',
        smooth: true,
        itemStyle: {
          color: '#409EFF'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(64, 158, 255, 0.2)' },
            { offset: 1, color: 'rgba(64, 158, 255, 0)' }
          ])
        }
      }
    ]
  }
  
  registerTrendChart.setOption(option)
}

// 渲染用户状态分布图表
const renderUserStatusChart = (data: any[]) => {
  if (!userStatusChartRef.value) return
  
  if (!userStatusChart) {
    userStatusChart = echarts.init(userStatusChartRef.value)
  }
  
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      bottom: '5%',
      left: 'center'
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['50%', '45%'],
        data: data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  userStatusChart.setOption(option)
}

// 渲染部门分布图表
const renderDeptDistributionChart = (data: any[]) => {
  if (!deptDistributionChartRef.value) return
  
  if (!deptDistributionChart) {
    deptDistributionChart = echarts.init(deptDistributionChartRef.value)
  }
  
  const option = {
    tooltip: {
      trigger: 'item'
    },
    series: [
      {
        type: 'pie',
        radius: '60%',
        data: data,
        label: {
          fontSize: 12
        }
      }
    ]
  }
  
  deptDistributionChart.setOption(option)
}

// 渲染角色分布图表
const renderRoleDistributionChart = (data: any[]) => {
  if (!roleDistributionChartRef.value) return
  
  if (!roleDistributionChart) {
    roleDistributionChart = echarts.init(roleDistributionChartRef.value)
  }
  
  const option = {
    tooltip: {
      trigger: 'item'
    },
    series: [
      {
        type: 'pie',
        radius: '60%',
        data: data,
        label: {
          fontSize: 12
        }
      }
    ]
  }
  
  roleDistributionChart.setOption(option)
}

// 获取活跃度颜色
const getActivityColor = (score: number) => {
  if (score >= 80) return '#67C23A'
  if (score >= 60) return '#E6A23C'
  return '#F56C6C'
}

// 日期范围变化
const handleDateChange = () => {
  refreshData()
}

// 趋势周期变化
const handleTrendPeriodChange = () => {
  getReportData()
}

// 搜索
const handleSearch = () => {
  queryForm.userName = searchText.value
  queryForm.pageNum = 1
  getUserData()
}

// 刷新数据
const refreshData = () => {
  getReportData()
  getUserData()
}

// 导出报表
const handleExport = async () => {
  try {
    const params = {
      startDate: dateRange.value?.[0] || '',
      endDate: dateRange.value?.[1] || '',
    }
    
    await exportUserReport(params)
    ElMessage.success('报表导出成功')
  } catch (error) {
    ElMessage.error('报表导出失败')
  }
}

// 生成模拟用户数据
const generateMockUserData = () => {
  const mockData = []
  const names = ['张三', '李四', '王五', '赵六', '钱七', '孙八', '周九', '吴十']
  const depts = ['研发部', '销售部', '财务部', '人事部', '市场部']
  const roles = ['管理员', '普通用户', '审核员', '操作员']
  
  for (let i = 0; i < 10; i++) {
    mockData.push({
      userName: `user_${i + 1}`,
      nickName: names[i % names.length],
      deptName: depts[i % depts.length],
      roleName: roles[i % roles.length],
      status: Math.random() > 0.8 ? '1' : '0',
      createTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toLocaleDateString(),
      lastLoginTime: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toLocaleDateString(),
      loginCount: Math.floor(Math.random() * 100) + 1,
      operCount: Math.floor(Math.random() * 500) + 10,
    })
  }
  
  return mockData
}

// 初始化
onMounted(() => {
  // 设置默认日期范围（最近30天）
  const today = new Date()
  const lastMonth = new Date(today.getTime() - 30 * 24 * 60 * 60 * 1000)
  dateRange.value = [
    lastMonth.toISOString().split('T')[0],
    today.toISOString().split('T')[0]
  ]
  
  refreshData()
  
  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    registerTrendChart?.resize()
    userStatusChart?.resize()
    deptDistributionChart?.resize()
    roleDistributionChart?.resize()
  })
})
</script>

<style lang="scss" scoped>
.user-report {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.report-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  .page-title {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin: 0;
  }
  
  .header-actions {
    display: flex;
    gap: 12px;
    align-items: center;
  }
}

.overview-row,
.charts-row,
.detail-row {
  margin-bottom: 20px;
}

.overview-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  
  .card-icon {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16px;
    
    .el-icon {
      font-size: 24px;
      color: white;
    }
    
    &.primary {
      background: linear-gradient(135deg, #409EFF, #6BB7FF);
    }
    
    &.success {
      background: linear-gradient(135deg, #67C23A, #95D475);
    }
    
    &.warning {
      background: linear-gradient(135deg, #E6A23C, #F0C674);
    }
    
    &.danger {
      background: linear-gradient(135deg, #F56C6C, #FF8A95);
    }
  }
  
  .card-content {
    .card-number {
      font-size: 28px;
      font-weight: 600;
      color: #303133;
      margin-bottom: 5px;
    }
    
    .card-label {
      font-size: 14px;
      color: #606266;
    }
  }
}

.chart-card,
.detail-card,
.table-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 600;
  }
  
  .table-actions {
    display: flex;
    gap: 12px;
    align-items: center;
  }
}

.chart-container {
  width: 100%;
  height: 300px;
}

.chart-container-small {
  width: 100%;
  height: 250px;
}

.activity-list {
  .activity-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .activity-user {
      font-weight: 500;
      color: #303133;
    }
    
    .activity-score {
      display: flex;
      align-items: center;
      gap: 8px;
      width: 120px;
      
      .el-progress {
        flex: 1;
      }
      
      .score-text {
        font-size: 12px;
        color: #606266;
        width: 35px;
        text-align: right;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .user-report {
    padding: 10px;
  }
  
  .report-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
    
    .header-actions {
      width: 100%;
      justify-content: center;
      flex-wrap: wrap;
    }
  }
  
  .overview-card {
    padding: 15px;
    margin-bottom: 10px;
  }
  
  .chart-container {
    height: 250px;
  }
  
  .chart-container-small {
    height: 200px;
  }
}
</style>

